package com.china08.yxyapi.api.manage.edu.platform.live.catalog;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.live.YxyLiveCatalog;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.repository.db.live.YxyLiveCatalogRepository;
import com.china08.yxyapi.util.StringTrimUtil;

import io.swagger.annotations.ApiOperation;

@CrossOrigin
@RestController
public class LiveCatalogCrtController extends YxyApiBaseController {

    @Autowired
    private YxyLiveCatalogRepository catalogRepository;

    @ApiOperation(value = "")
    @RequestMapping(value = "/api_yw/manage/edu/platform/live/catalog/crt", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void precess(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {
        String catalogPid = reqModel.catalogPid;
        String catalogName = reqModel.catalogName;
        catalogName = StringTrimUtil.trim(catalogName);
        Integer catalogLeave = reqModel.catalogLeave;
        String schoolId = getProfile(request, response).getSchoolId();

        // 获取当前级别目录总个数
        Integer count = catalogRepository.countBySchoolIdAndLevelAndPid(schoolId, catalogLeave, catalogPid);
        Assert.isTrue(count < 20, "每级分类可以添加20个栏目");

        YxyLiveCatalog catalog = new YxyLiveCatalog();
        catalog.setLevel(catalogLeave);
        catalog.setName(catalogName);
        catalog.setPid(catalogPid);
        catalog.setSchoolId(schoolId);

        // 获取栏目排序字段
        catalog.setOrderNum(20);
        catalogRepository.save(catalog);
    }

    public static class ReqModel extends YxyApiReqModel {
        public String catalogName;
        public Integer catalogLeave;
        public String catalogPid;

        @Override
        public void autoCheck() {
            // 去除空格
            catalogName = StringTrimUtil.trim(catalogName);
            Assert.isTrue(StringUtils.isNotBlank(catalogName), "请输入1-8个字的分类名称");
            Assert.isTrue(catalogLeave != null && catalogLeave > 0, "栏目分类为空");
        }
    }
}
